package com.ray.test.proxy.asm;

import lombok.extern.slf4j.Slf4j;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;

import java.lang.reflect.Method;

/**
 * @author bo shen
 * @Description: asm Aop
 * @Class: AsmAopGenerator
 * @Package com.ray.test.proxy.asm
 * @date 2019/12/20 11:08
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class AsmAopGenerator {
    private AOPGeneratorClassLoader classLoader;

    public AsmAopGenerator() {
        classLoader = new AOPGeneratorClassLoader();
    }


    public Object proxy(Class c, Method method) {
        try {
            if (c != null) {
                String classPach = c.toString().replace("/", ".");
                ClassReader cr = new ClassReader(classPach.substring(6, classPach.length()));
                ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
                AsmAopClassAdapter classAdapter = new AsmAopClassAdapter(cw, method);
                cr.accept(classAdapter, ClassReader.SKIP_DEBUG);
                byte[] data = cw.toByteArray();
                Class obj = classLoader.defineClassFromClassFile(classAdapter.getEnhancedName(), data);
                return obj.newInstance();
            }
        } catch (Exception e) {
           log.info("asm创建异常");
        }
        return null;
    }


    class AOPGeneratorClassLoader extends ClassLoader {
        public Class defineClassFromClassFile(String className,
                                              byte[] classFile) throws ClassFormatError {
            return defineClass(className, classFile, 0,
                    classFile.length);
        }
    }
}
